# set working directory to location of the R file
#setwd("replication/scripts")

require(devtools)
# uncomment if not installed in previous file:
#devtools::install_github("ChandlerLutz/starpolishr")
library(starpolishr)

require(pacman)

pacman::p_load(tidyverse, lfe, dplyr, ggplot2, ggpubr, stargazer, PanelMatch, purrr, cowplot,did,DRDID,
               purrr)

# combined panel
load("../Data/combined_panel.RData")

combined_panel <- as.data.frame(combined_panel)
combined_panel$period <- as.integer(combined_panel$period)
combined_panel$log_rev <- log(combined_panel$revenue)

# check staff and bureau covariates are the same
cor(combined_panel$total_bur_filings, combined_panel$total_staff_filings)
combined_panel$log_contracts <- log(combined_panel$total_bur_filings)
combined_panel$log_lobby <- log(combined_panel$total_bur_lobbyists)

# create treatment indicator
combined_panel$treat <- ifelse(combined_panel$prev_exp == 1 | combined_panel$staff_exp == 1, 1, 0)
combined_panel$treat <- ifelse(is.na(combined_panel$treat)==T,0,combined_panel$treat)


#############
# wrapper function for PanelMatch

pm_year <- function(lags, dataset, treat,
                    DV, time_var){
  
  this_data <- dplyr::filter(dataset, period %in% (time_var-6):(time_var+4))
  
    comb <- PanelMatch(lag = lags, 
                       time.id = "period", unit.id = "reg_lobby_core_id", 
                       treatment = treat, 
                       refinement.method = "none", 
                       data = this_data, 
                       match.missing = T, 
                       qoi = "att" ,
                       outcome.var = DV,
                       lead = 0:4, 
                       forbid.treatment.reversal = T)
    
    dist_control <- comb$att
    comb_obs <- sum(print(comb$att)[,3])
  
  
  comb_results <- PanelEstimate(sets = comb, 
                                data = this_data, 
                                confidence.level = .9)
  
  pm_res <- as.data.frame(summary(comb_results)[[1]][1:5, 1:2])
  
  pm_res <- data.frame(pm_res, time_var, t_since_treat = 0:4)
  
  return(pm_res)
  
}

att_time <- map_df(7:36,
                   ~ pm_year(lags = 4, dataset = combined_panel,
                             treat = "treat",
                             DV = "log_rev", time_var = .))

att_time$time <- 0:4

att_time <- filter(att_time, time == 0)

ggplot(att_time, aes(x = time_var, y = estimate)) +
  geom_point() +
  theme_classic() + 
  geom_errorbar(aes(ymin = estimate - 1.645*std.error,
                    ymax = estimate + 1.645*std.error),width = 0)  +
  geom_hline(yintercept = 0, lty = 3) +
  scale_x_continuous(breaks = 7:36) +
  labs(x = "Time Period",
       y = "Difference-in-Differences\n(Contemporaneous Effect)")

  ggsave(filename = "../images/FigureB4.pdf",
         width = 8, heigh = 6)

min(att_time$estimate)
max(att_time$estimate)
mean(att_time$estimate)

mean(att_time$estimate) - (max(att_time$estimate) - min(att_time$estimate))

0.35 - (max(att_time$estimate) - min(att_time$estimate))




#---------------------------------
# Time-Varying Effects conditional on partisanship

load("../Data/firm_experience_panels.RData")


###
# staff
staff_exp_firm <- as.data.frame(staff_exp_firm)
staff_exp_firm$period <- as.integer(staff_exp_firm$period)
staff_exp_firm$log_rev <- log(staff_exp_firm$revenue)

# check staff and bureau covariates are the same
staff_exp_firm$log_contracts <- log(staff_exp_firm$total_filings)
staff_exp_firm$log_lobby <- log(staff_exp_firm$total_lobbyists)

# create treatment indicator
staff_exp_firm$staff_exp2 <- ifelse(is.na(staff_exp_firm$staff_exp)==T,0,staff_exp_firm$staff_exp)



# add partisanship indictor
load("../Data/staff_party.RData")

staff_firms_party_panel <- select(staff_firms_party_panel, reg_lobby_core_id, period, any_dem)

staff_exp_firm <- left_join(staff_exp_firm, staff_firms_party_panel, 
                            by = c("reg_lobby_core_id", "period"))

staff_exp_firm$any_dem <- ifelse(is.na(staff_exp_firm$any_dem) == T, -1, 
                                 staff_exp_firm$any_dem)

d_vs_control <- filter(staff_exp_firm, any_dem == 1 | any_dem == -1)
r_vs_control <- filter(staff_exp_firm, any_dem == 0 | any_dem == -1)

d_vs_control$period <- as.integer(d_vs_control$period)

# deal with low number of treatment events
poss_pm_year <- possibly(.f = pm_year, otherwise = NA)

# run
d_att_time <- map(7:36,
                   ~ poss_pm_year(lags = 4, dataset = d_vs_control,
                             treat = "staff_exp2",
                             DV = "log_rev", time_var = .))
d_att_time <- do.call("rbind", d_att_time)

# Republican and cmte staf
r_vs_control$period <- as.integer(r_vs_control$period)

r_att_time <- map(7:36,
                     ~ poss_pm_year(lags = 4, dataset = r_vs_control,
                                    treat = "staff_exp2",
                                    DV = "log_rev", time_var = .))
r_att_time <- do.call("rbind", r_att_time)

# plot results
d_att_time <- filter(d_att_time, t_since_treat == 0)

p_dem <- ggplot(d_att_time, aes(x = time_var, y = estimate)) +
  geom_point() +
  theme_classic() + 
  geom_errorbar(aes(ymin = estimate - 1.645*std.error,
                    ymax = estimate + 1.645*std.error),width = 0)  +
  geom_hline(yintercept = 0, lty = 3) +
  scale_x_continuous(breaks = 7:36) +
  labs(x = "Time Period",
       y = "Difference-in-Differences\n(Contemporaneous Effect)",
       title = "A: Democrats") 

  # ggsave(filename = "images/DemTime.eps",
  #        device = cairo_ps,
  #        width = 8, heigh = 6)

r_att_time <- filter(r_att_time, t_since_treat == 0)

p_oth <- ggplot(r_att_time, aes(x = time_var, y = estimate)) +
  geom_point() +
  theme_classic() + 
  geom_errorbar(aes(ymin = estimate - 1.645*std.error,
                    ymax = estimate + 1.645*std.error),width = 0)  +
  geom_hline(yintercept = 0, lty = 3) +
  scale_x_continuous(breaks = 7:36) +
  labs(x = "Time Period",
       y = "Difference-in-Differences\n(Contemporaneous Effect)",
       title = "B: Republicans and Committee Staff") 
  # ggsave(filename = "images/RepTime.eps",
  #        device = cairo_ps,
  #        width = 8, heigh = 6)

p_part <- plot_grid(p_dem, p_oth, nrow = 2)
p_part


ggsave(plot= p_part, filename = "../images/FigureD9.pdf",
       width = 8, height = 8)






